<template>
  <div class="zh-notice">
    <div class="zh-notice-g" v-if="cateData.length > 0">
      <el-tabs v-model="activeName" type="card" @tab-click="changeTab">
        <el-tab-pane :label="item.name" :name="inx + ''" v-for="(item, inx) in cateData" :key="inx">
          <ul>
            <li class="i_hNotice" v-for="(item2, inx2) in bulletinList" :key="inx2">
              <a href="###">{{item2.name}}</a>
              <span>{{item2.update_time.split(' ')[0]}}</span>
            </li>
          </ul>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="zh-notice-b">
      <el-tabs v-model="activeTabli">
        <el-tab-pane label="公告管理" name="1">
          <el-table
            :data="listData"
            fixed
            border
            ref="multipleTable"
            @selection-change="tableSelectionChange"
            max-height="600"
            style="width: 100%"
          >
            <el-table-column type="selection" width="50" fixed></el-table-column>
            <el-table-column prop="name" label="标题" show-overflow-tooltip></el-table-column>
            <el-table-column prop="category_name" label="分类" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="username" label="作者" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sort" label="排序" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="状态" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-if="parseInt(scope.row.status) === 2" type="text" size="small">关闭</span>
                <span v-if="parseInt(scope.row.status) === 1" type="text" size="small">开启</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <el-button @click="newNoticeRouter(scope.row.id)" type="text" size="small">编辑</el-button>
                <el-button
                  type="text"
                  @click="delete_confirm(scope.row)"
                  class="delete-button"
                  size="small"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-pagination" v-show="total_number > 5">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="listParam.page_index"
              :page-sizes="[5, 10, 15, 20, 25, 50]"
              :page-size="listParam.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total_number"
            ></el-pagination>
          </div>
        </el-tab-pane>

        <el-tab-pane label="公告分类" name="2">
          <el-table
            :data="cateData"
            fixed
            border
            @selection-change="tableSelectionChange"
            style="width: 100%"
          >
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="name" label="分类名"></el-table-column>
            <el-table-column prop label="状态">
              <template slot-scope="scope">
                <span v-if="parseInt(scope.row.status) === 2" type="text" size="small">已禁用</span>
                <span v-if="parseInt(scope.row.status) === 1" type="text" size="small">已启用</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
              <template slot-scope="scope">
                <el-button
                  @click="changeCate_confirm(scope.row,2)"
                  v-if="parseInt(scope.row.status) === 1"
                  type="text"
                  size="small"
                >禁用</el-button>
                <el-button
                  @click="changeCate_confirm(scope.row,1)"
                  v-if="parseInt(scope.row.status) === 2"
                  type="text"
                  size="small"
                >启用</el-button>
                <el-button type="text" @click="saveCateBox(scope.row)" size="small">编辑</el-button>
                <el-button
                  type="text"
                  @click="deleteCate_confirm(scope.row)"
                  class="delete-button"
                  size="small"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div class="zh-notice-vp" v-if="activeTabli === '1' ">
        <el-button type="primary" @click="newNoticeRouter(null)">添加公告</el-button>
        <el-button type="danger" @click="deleteMuilt_confirm">删除所选</el-button>
      </div>
      <div class="zh-notice-vp" v-if="activeTabli === '2' ">
        <el-button type="primary" @click="saveCateBox(null)">添加分类</el-button>
      </div>
      <div class="notice-search-box" v-show="activeTabli == '1'">
        <el-input placeholder="请输入标题搜索" v-model="listParam.keyword" clearable @clear="searchList">
          <el-button slot="append" icon="el-icon-search" @click="searchList"></el-button>
        </el-input>
      </div>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="cateCancel"
      :title="cateTitle"
      :visible.sync="addCate"
      class="addRole"
      width="450px"
    >
      <el-form
        :model="addForm"
        ref="addForm"
        status-icon
        :rules="cateRules"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入分类名称，不超过个10个字符"
            autocomplete="off"
            maxlength="10"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="cateCancel">取消</el-button>
        <el-button size="medium" type="primary" @click="saveCate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rowLen: 0,
      selected: [],
      cateTitle: "添加分类",
      addCate: false,
      cateData: [],
      activeName: "0",
      activeTabli: "1",
      multipleSelection: [],
      addForm: {
        name: "",
      },
      cateRules: {
        name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
          {
            pattern: /^\S+$/,
            message: "名称不可包含空格",
            trigger: "blur",
          },
        ],
      },
      listData: [],
      listParam: {
        page_index: 1,
        page_size: 5,
        keyword: "",
        status: [1, 2],
      },
      total_number: 0,
      bulletinList: [], // 某个分类下所有公告
      bullentinId: 0,
    };
  },
  created() {
    this.getList();
    this.getCategory();

    if( !is_empty( this.$store.getters.activePanel ) ){
        this.activeTabli = '2'
    }
  },
  destroyed() {
    this.$store.commit("SET_ACTIVEPANEL", null);
  },
  methods: {
    /**
     * 获取某个分类下所有公告
     */
    getBulletin() {
      let success = (res) => {
        this.bulletinList = res.data.data;
      };

      let fail = (res) => {};
      let params = {
        category_id: this.bullentinId,
        order: "sort",
      };

      this.$ajax.get("api/news/news_list", {
        params,
        func: { success: success, fail: fail },
      });
    },
    /**
     * 切换选项卡
     */
    changeTab(tab, event) {
      this.bullentinId = this.cateData[tab.index].id;
      this.bulletinList = [];
      this.getBulletin();
    },
    cateCancel() {
      this.$refs.addForm.clearValidate();
      this.addForm.name = "";
      this.addCate = false;
    },
    /**
     * 根据条件搜索
     * @change 2019-5-6
     */
    searchList() {
      this.listParam.page_index = 1;
      this.getList();
    },
    getList() {
      // 重写成功回调
      let success = (data) => {
        this.listData = data.data.data;
        this.total_number = data.data.data_sum;
      };
      this.$ajax.get("api/news/news_list", {
        params: this.listParam,
        func: {
          success: success,
        },
      });
    },
    delete_confirm(obj) {
      let yes = (data) => {
        let success = (data) => {
          this.$message.success(data.msg);

          if (this.listData.length - 1 === 0) {
            if (this.listParam.page_index > 1) {
              this.listParam.page_index--;
            } else {
              this.listParam.page_index = 1;
            }
          }

          if (obj.category_name === this.cateData[this.activeName].name) {
            this.getBulletin();
          }

          this.getList();
        };
        this.$ajax.delete("api/news/news", {
          params: {
            id: obj.id,
          },
          func: {
            success: success,
          },
        });
      };
      let cancel = (data) => {};
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将 " + obj.name + " 删除吗？",
      });
    },
    deleteMuilt_confirm() {
      if (this.selected.length === 0) {
        this.$message.warning("请选择要删除的项");
        return false;
      }
      this.rowLen = this.selected.length;
      let yes = (data) => {
        var ids = [];
        for (var i = this.selected.length - 1; i >= 0; i--) {
          ids.push(this.selected[i].id);
        }
        let success = (data) => {
          this.$message.success(data.msg);

          if (this.listData.length - this.rowLen === 0) {
            if (this.listParam.page_index > 1) {
              this.listParam.page_index--;
            } else {
              this.listParam.page_index = 1;
            }
          }

          this.getList();
        };
        this.$ajax.delete("api/news/news", {
          params: {
            id: ids,
          },
          func: {
            success: success,
          },
        });
      };
      let cancel = (data) => {};
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将删除选中的项吗？",
      });
    },
    deleteCate_confirm(obj) {
      let yes = (data) => {
        let success = (data) => {
          this.$message.success(data.msg);
          this.activeName = "0";
          this.getCategory();
        };
        this.$ajax.delete("api/news/category", {
          params: {
            id: obj.id,
          },
          func: {
            success: success,
          },
        });
      };
      let cancel = (data) => {};
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将 " + obj.name + " 删除吗？",
      });
    },
    changeCate_confirm(obj, status) {
      var status_txt = status === 1 ? "启用" : "禁用";
      let yes = (data) => {
        let success = (data) => {
          this.$message.success(data.msg);
          this.getCategory();
        };
        this.$ajax.post(
          "api/news/category_status",
          {
            id: obj.id,
            status: status,
          },
          {
            func: {
              success: success,
            },
          }
        );
      };
      let cancel = (data) => {};
      this.e_confirm({
        yes: yes,
        cancel: cancel,
        txt: "确定将 " + obj.name + " " + status_txt + "吗？",
      });
    },
    saveCate() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let success = (data) => {
            this.$message.success(data.msg);
            this.getCategory();
            this.addCate = false;

            if (+this.addForm.id > 0) {
              this.getList();
            }
          };
          if (parseInt(this.addForm.id) > 0) {
            this.$ajax.put("api/news/category", this.addForm, {
              func: {
                success: success,
              },
            });
          } else {
            this.$ajax.post("api/news/category", this.addForm, {
              func: {
                success: success,
              },
            });
          }
        } else {
          return false;
        }
      });
    },
    saveCateBox(obj = null) {
      if (is_empty(obj)) {
        this.cateTitle = "添加分类";
        this.addForm.id = 0;
        this.addForm.name = "";
      } else {
        this.cateTitle = "编辑分类";
        this.addForm.id = obj.id;
        this.addForm.name = obj.name;
      }
      this.addCate = true;
    },
    getCategory() {
      // 重写成功回调
      let success = (data) => {
        this.cateData = data.data;

        if (!is_empty(data.data)) {
          this.bullentinId = this.cateData[0].id;
          this.getBulletin();
        }
      };
      this.$ajax.get("api/news/category", {
        func: {
          success: success,
        },
      });
    },
    /**
     * 切换每页的条数
     * @param {Number} val 每页条数
     */
    handleSizeChange(val) {
      this.listParam.page_index = 1;
      this.listParam.page_size = val;
      this.getList();
    },
    /**
     * 切换当前页
     * @param  {Number} val 要跳转的页数
     */
    handleCurrentChange(val) {
      this.listParam.page_index = val;
      this.getList();
    },
    /**
     * 添加/编辑公告
     * @param {Number} id 公告id
     */
    newNoticeRouter(id) {
      if (!is_empty(id)) {
        this.$router.push("/portal/show/newNotice/" + id);
      } else {
        this.$router.push("/portal/show/newNotice");
      }
    },
    /**
     * 表格多选
     * @param {Array} val 选中的数组
     */
    tableSelectionChange(val) {
      this.selected = val;
    },
  },
};
</script>

<style lang="scss">
.zh-notice {
  .el-tabs--top .el-tabs__item.is-top:nth-child(2) {
    padding-left: 20px;
  }

  .el-tabs--top .el-tabs__item.is-top:last-child {
    padding-right: 20px;
  }

  .zh-notice-g {
    padding: 25px 0;
    min-height: 200px;
    max-height: 392px;
    background: #eeeeee;

    .el-tabs {
      margin: 0 20px;
      padding: 20px 10px;
      background: #fff;
    }

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__content {
      max-height: 300px;
      overflow-y: auto;
    }

    .i_hNotice {
      display: flex;
      justify-content: space-between;
      padding: 0 5px;
      height: 38px;
      line-height: 38px;
      border-bottom: solid 1px #e5e5e5;

      > a {
        display: block;
        font-size: 14px;
        max-width: 70%;
      }

      > span {
        color: #888888;
      }
    }
  }

  .zh-notice-b {
    position: relative;
    margin-top: 40px;
    // width: 99.9%;

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .is-active {
      background: none;
      color: #409eff;
    }

    .el-icon-close {
      color: red;
      font-size: 16px;
    }

    .el-icon-check {
      color: #409eff;
      font-size: 16px;
    }

    .zh-notice-vp {
      position: absolute;
      top: 0;
      right: 0;
    }

    #pane-1 {
      margin-top: 50px;
    }
  }

  .notice-search-box {
    position: absolute;
    top: 50px;
    left: 0;
  }
}
</style>